package cn.tedu.homework_weibo.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.tedu.homework_weibo.common.JsonResult;
import cn.tedu.homework_weibo.common.StatusCode;
import cn.tedu.homework_weibo.mapper.WeiboMapper;
import cn.tedu.homework_weibo.pojo.dto.WeiboDTO;
import cn.tedu.homework_weibo.pojo.entity.Weibo;
import cn.tedu.homework_weibo.pojo.vo.UserVO;
import cn.tedu.homework_weibo.pojo.vo.WeiboDetailVO;
import cn.tedu.homework_weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Api(tags = "02.微博模块")
@RestController
@Slf4j
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @PostMapping("insert")
    @ApiOperation("发布微博")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        log.debug("weiboDTO=" + weiboDTO);
        //校验登录状态
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUser_id(userVO.getId());
        weiboMapper.insert(weibo);
        return JsonResult.ok();
    }

    @ApiOperation("微博首页列表")
    @GetMapping("selectIndex")
    public JsonResult selectIndex() {
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
        return JsonResult.ok(weiboIndexVOS);
    }

    @ApiOperation("查看微博详情")
    @GetMapping("selectById")
    public JsonResult selectById(@RequestParam Integer id) {
        log.debug("id=" + id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        return JsonResult.ok(weiboDetailVO);
    }
}
